package com.beerandjesus.sportofkings.handicapper.strategy;

import com.beerandjesus.sportofkings.handicapper.model.CramerJockeyRating;
import com.beerandjesus.sportofkings.handicapper.model.JockeyAtDistanceOrOnTurf;
import com.beerandjesus.sportofkings.handicapper.model.TrainerJockeyOwner;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.math.MathContext;

/**
 * Date: Jun 23, 2012
 * Time: 5:45:59 PM
 */
public class CramerJockeyRatingResolverImpl implements CramerJockeyRatingResolver {
    private static final Logger LOG = Logger.getLogger(CramerJockeyRatingResolverImpl.class);

    public CramerJockeyRating getRating(TrainerJockeyOwner tjo, JockeyAtDistanceOrOnTurf jock) {
        if (tjo == null && jock == null) {
            return CramerJockeyRating.UNKNOWN;
        }
        if (tjo != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rating " + tjo.getJockeyName() + " by current meet stats");
            }
            try {
                return getRating(tjo.getJockeyCurrentMeetStarts(), tjo.getJockeyCurrentMeetWins());
            } catch (EarlyInTheMeetException e) {
                // Okay
            }
        }
        if (jock == null) {
            return CramerJockeyRating.UNKNOWN;
        }
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rating jockey by at distance/on turf stats");
            }
            return getRating(jock.getStarts(), jock.getWins());
        } catch (EarlyInTheMeetException e) {
            return CramerJockeyRating.UNKNOWN;
        }

    }

    private CramerJockeyRating getRating(String s, String w) throws EarlyInTheMeetException {
        BigDecimal starts = null;
        try {
            starts = new BigDecimal(s);
        } catch (Exception e) {
            // Ignore
        }
        if (starts == null || starts.compareTo(new BigDecimal(10)) < 0) {
            throw new EarlyInTheMeetException();
        }
        BigDecimal wins = null;
        try {
            wins = new BigDecimal(w);
        } catch (Exception e) {
            // Ignore
        }
        if (wins != null) {
            BigDecimal winPercentage = wins.divide(starts, MathContext.DECIMAL32);
            CramerJockeyRating r = CramerJockeyRating.OTHER;
            if (winPercentage.compareTo(new BigDecimal(.22)) > 0) {
                r = CramerJockeyRating.LEADING;
            } else if (winPercentage.compareTo(new BigDecimal(.17)) > 0) {
                r = CramerJockeyRating.EXCELLENT;
            } else if (winPercentage.compareTo(new BigDecimal(.11)) > 0) {
                r = CramerJockeyRating.GOOD;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug(wins + " / " + starts + " = " + winPercentage + " = " + r);
            }
            return r;
        }
        return CramerJockeyRating.UNKNOWN;
    }

}
